<script setup lang="ts">
import { h, reactive, ref } from 'vue';
import type { FormInst } from 'naive-ui';
import { NButton, useMessage } from 'naive-ui';
import { useAppStore } from '@/store/modules/app';
import { REQUEST } from '@/api/request';
const emit = defineEmits(['ok']);
const message = useMessage();
const appStore = useAppStore();
const formRef = ref<FormInst | null>(null);
const showModal: any = ref(false);
const title: any = ref('');
const disable = ref(false);
const loading = ref(false);
const formValue: any = ref({
  id: '',
  userName: '',
  list: null,
  deliverTime: null
});
const productList: any = ref([]);
const options = ref([]);
const shoppingList = () => {
  REQUEST.POST('ORDERSHOP', {}).then((res: any) => {
    options.value = res.data.products;
    options.value.map((item: any) => {
      item.label = item.name;
      item.value = item.id;
    });
  });
};
const open = (titles: string, data: any) => {
  formValue.value = {
    id: '',
    userName: '',
    list: null,
    deliverTime: null
  };
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  shoppingList();
  productList.value = [];
  title.value = titles;
  disable.value = false;
  showModal.value = true;
  if (titles === '编辑订单') {
    console.log(data);
    disable.value = true;
    // eslint-disable-next-line @typescript-eslint/no-use-before-define

    const arr: any = [];
    productList.value = data.productList;

    data.productList.map((pro: any) => {
      arr.push(pro.productId);
    });
    formValue.value = {
      id: data.id,
      userName: data.userName,
      list: [...arr],
      deliverTime: data.deliverTime
    };
  }
};

const rules: any = ref({
  userName: {
    required: true,
    message: '请输入姓名',
    trigger: 'blur'
  },
  deliverTime: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择时间'
  },
  list: {
    required: true,
    type: 'array',
    message: '请选择商品',
    trigger: ['blur']
  }
});
const handleCancel = () => {
  formValue.value = {
    id: '',
    userName: '',
    list: null,
    deliverTime: null
  };
  loading.value = false;
  disable.value = false;
  showModal.value = false;
};
const OrderFun = (apiName: string) => {
  loading.value = true;
  const arr: any = [];
  productList.value.map((item: any) => {
    arr.push(`${item.name}(${item.num})`);
  });
  REQUEST.POST(apiName, {
    userName: formValue.value.userName,
    deliverTime: formValue.value.deliverTime,
    id: formValue.value.id ? formValue.value.id : '',
    orderProductList: productList.value,
    remark: arr.join(',')
  }).then((res: any) => {
    loading.value = false;
    message.success('操作成功！');
    emit('ok');
    handleCancel();
  });
};
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(errors => {
    if (!errors) {
      if (title.value == '新增订单') {
        OrderFun('ORDERADD');
      } else {
        OrderFun('ORDEREDIT');
      }
    } else {
      message.warning('请完善表单');
    }
  });
};
const actionsArr: any = [
  {
    title: '+',
    key: 'edit'
  },
  {
    title: '-',
    key: 'del'
  }
];
const columns: any = reactive([
  {
    title: '商品名称',
    key: 'name',
    minWidth: 100
  },
  {
    title: '购买数量',
    key: 'num',
    minWidth: 80
  },
  {
    title: '未出库数量',
    key: 'undelivered',
    minWidth: 80
  },
  {
    title: '出库数量',
    key: 'dataVersion',
    minWidth: 80
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    minWidth: 100,
    render(row: any) {
      const buttonGroup = actionsArr.map((item: any) => {
        return h(
          NButton,
          {
            size: 'small',
            type: item.key === 'edit' ? 'primary' : 'error',
            style: {
              marginRight: '6px'
            },
            onClick: () => {
              if (item.key === 'edit') {
                // eslint-disable-next-line @typescript-eslint/no-use-before-define
                add(row);
              } else {
                // eslint-disable-next-line @typescript-eslint/no-use-before-define
                prve(row);
              }
            }
          },
          {
            default: () => item.title
          }
        );
      });

      return buttonGroup;
    }
  }
]);
const add = (row: any) => {
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  productList.value.map((item: any) => {
    if (item.name == row.name) {
      item.num += 1;
      item.undelivered = item.dataVersion ? item.num - item.dataVersion : item.num;
    }
  });
};
const prve = (row: any) => {
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  productList.value.map((item: any) => {
    if (item.name == row.name) {
      if (item.num > 1) {
        item.num -= 1;
        item.undelivered = item.dataVersion ? item.num - item.dataVersion : item.num;
      } else {
        message.error('商品数量不能少于1');
      }
    }
  });
};
// blur
const selectShop = () => {
  const arr: any = [];
  options.value.map((item: any) => {
    formValue.value.list.map((li: any) => {
      if (item.value == li) {
        const objs: any = {
          name: item.label,
          productId: item.value,
          num: li.num ? li.num : 1,
          undelivered: li.num
        };
        arr.push(objs);
      }
    });
  });
  productList.value = [...arr];
};
// change
const selectShops = (e: any) => {
  const arr: any = [];
  options.value.map((item: any) => {
    e.map((li: any) => {
      if (item.value == li) {
        const objs: any = {
          name: item.label,
          productId: item.value,
          num: li.num ? li.num : 1,
          undelivered: li.num
        };
        arr.push(objs);
      }
    });
  });
  productList.value = [...arr];
};
defineExpose({ open });
</script>

<template>
  <NModal
    v-model:show="showModal"
    :style="{ width: !appStore.isMobile ? '700px' : '100%' }"
    class="custom-card"
    preset="card"
    :title="title"
  >
    <NCard :bordered="false" size="huge" role="dialog" aria-modal="true">
      <template #header-extra>x</template>
      <NForm
        ref="formRef"
        :label-width="80"
        :model="formValue"
        :rules="rules"
        :label-placement="!appStore.isMobile ? 'left' : 'top'"
      >
        <NFormItem label="姓名" path="userName">
          <NInput v-model:value="formValue.userName" placeholder="请输入姓名" />
        </NFormItem>
        <NFormItem label="选择商品" path="list">
          <NSelect
            v-model:value="formValue.list"
            filterable
            multiple
            :disabled="disable"
            :options="options"
            @update-value="selectShops"
            @blur="selectShop"
          />
        </NFormItem>
        <NFormItem label="商品列表">
          <NDataTable :columns="columns" :data="productList" :bordered="true"></NDataTable>
        </NFormItem>

        <NFormItem label="交货日期" path="deliverTime">
          <NDatePicker
            v-model:formatted-value="formValue.deliverTime"
            :disabled="disable"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
            type="datetime"
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NFlex justify="end">
          <NButton @click="handleCancel">取消</NButton>
          <NButton type="primary" :disabled="loading" :loading="loading" @click="handleValidateClick">确定</NButton>
        </NFlex>
      </template>
    </NCard>
  </NModal>
</template>
